<template>
  <div class="container-publish">
    <el-card>
      <div slot="header">
        <my-bread style="margin-bottom:20px">{{$route.query.id?'修改文章':'发布文章'}}</my-bread>
      </div>
      <!-- 表单 -->
      <el-form ref="articleForm" :model="articleForm" :rules="articleRules" label-width="120px">
        <el-form-item label="标题:" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" style="width:400px"></el-input>
        </el-form-item>
        <!-- 内容 -->
        <el-form-item label="内容：" prop="content">
          <quill-editor
            @blur="checkContent()"
            v-model="articleForm.content"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="封面:" prop="cover">
          <el-radio-group @change="articleForm.cover.images = []" v-model="articleForm.cover.type">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
          <!-- 封面组件
          分情况讨论
          -->
          <!-- 单图模式 -->
          <div style="height:162px" v-if="articleForm.cover.type === 1">
            <my-image v-model="articleForm.cover.images[0]"></my-image>
          </div>
          <!-- 三图模式 -->
          <div style="height:162px" v-if="articleForm.cover.type === 3">
            <my-image v-model="articleForm.cover.images[i-1]" v-for="i in 3" :key="i"></my-image>
          </div>
        </el-form-item>
        <el-form-item label="频道:" prop="channel_id">
          <my-channel v-model="articleForm.channel_id"></my-channel>
        </el-form-item>
        <!-- 发布和修改文章 -->
        <el-form-item v-if="$route.query.id">
          <el-button @click="editArticle()" type="success">修改文章</el-button>
        </el-form-item>
        <el-form-item v-else>
          <el-button type="primary" @click="addArticle(false)">发布文章</el-button>
          <el-button @click="addArticle(true)">存入草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
export default {
  name: "publish-page",
  components: {
    // 进行组件注册
    quillEditor
  },
  created() {
    // 只要路径存在id就会进行刷新
    if (this.$route.query.id) {
      
      this.getArticle();
    }
  },
  data() {
    // 检验函数
    const checkCover = (rule, value, callback) => {
      // 判断是否选择了封面图

      // 单图模式
      if (value.type === 1) {
        if (!value.images[0]) {
          return callback(new Error("请选择一张封面图"));
        }
      }

      // 三图模式
      if (value.type === 3) {
        if (!value.images[0] || !value.images[1] || !value.images[2]) {
          return callback(new Error("请选择三张图片"));
        }
      }
      callback();
    };
    return {
      // 文章表单数据
      articleForm: {
        title: null,
        cover: {
          type: 1,
          // 图片资源
          images: []
        },
        channle_id: null,
        content: null
      },
      imgUrl: null,
      // 富文本
      editorOption: {
        placeholder: "请输入文章内容",
        modeles: {
          // 工具栏
          toolbar: [
            ["bold", "italic", "underline", "strike"],
            ["blockquote", "code-block"],
            [{ header: 1 }, { header: 2 }],
            [{ list: "ordered" }, { list: "bullet" }],
            [{ indent: "-1" }, { indent: "+1" }],
            ["image"]
          ]
        }
      },
      // 校验规则
      articleRules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          { min: 5, max: 30, message: "文章标题5-30字符", trigger: "blur" }
        ],
        content: [
          { required: true, message: "请输入文章内容", trigger: "blur" }
        ],
        cover: [{ validator: checkCover, trigger: "blur" }],
        channel_id: [
          { required: true, message: "请选择所属频道", trigger: "change" }
        ]
      }
    };
  },
  // 监听器
  watch: {
    "articleForm.cover": {
      // 数据变化执行处理函数
      handler() {
        this.$nextTick(()=>{
           this.$refs.articleForm.validateField("cover");
        })
       
      },
      // 深度监听
      deep: true
    },
    '$route.query.id':function(){
      if(this.$route.query.id){
        this.getArticle()
      }else{
        // 重置表单
        this.articleForm = {
          title: null,
          cover: {
            type: 1,
            images: []
          },
          channel_id: null,
          content: null
        }
        // 清除 cover channel_id 的校验样式
        setTimeout(() => {
          this.$refs.articleForm.clearValidate(['cover', 'channel_id'])
        }, 0)

      }
    }
  },
  methods: {
   
    // 修改文章
    editArticle () {
      this.$refs.articleForm.validate(async valid => {
        try{
          // 发送修改请求
          await this.$http({
            method:'put',
            url:`/articles/${this.$route.query.id}`,
            params:{
              draft:false
            },
            // 请求体传参
            data:this.articleForm
          })
          // 提示
          this.$message.success('修改文章成功')
          // 跳转内容管理
          this.$router.push('/article')
        }catch(e){
          // 失败提示
          this.$message.error('修改文章失败')
        }
      })
    },
    // 校验富文本
    checkContent() {
      this.$refs.articleForm.validateField("content");
    },
    // 获取文章
    async getArticle () {
      const {data:{data}} = await this.$http.get('/articles/' + this.$route.query.id)
      // 填充表单
      this.articleForm = data
    },
    // 添加文章
    addArticle(draft) {
      // 表单校验
      this.$refs.articleForm.validate(async valid => {
        if (valid) {
          try {
            await this.$http.post(`/articles?draft=${draft}`, this.articleForm);
            this.$message.success(draft ? "存入草稿成功" : "发布文章成功");
            this.$router.push("/article");
          } catch (e) {
            this.$message.error(draft ? "存入草稿失败" : "发布文章失败");
          }
        }
      });
    }
  }
};
</script>
<style scoped lang='less'>
// /deep/深度作用
/deep/ .ql-toolbar.ql-snow {
  padding: 0 8px;
}
/deep/ .ql-editor {
  height: 250px;
}
</style>